﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web.Services;
using System.Web.Security;
using System.Collections;
using System.ComponentModel;
using System.Web.Services.Description;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Text;
using System.Transactions;
using WebServiceSmart.Router;
using Thrift.Transport;
using Thrift.Protocol;
using Thrift.Route;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using log4net;
using System.Security.Cryptography;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
using WebServiceSmart.Model;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Reflection;
namespace WebServiceSmart
{
    public struct CheckNetInfo
    {
        public string Companyname;
        public string Companyaccount;
        public string Netname;
        public string Netaccount;
        public string Ygname;
        public string Ygaccount;
        public string Device;
    };

    public class SmsSendInterface
    {
        // 余额信息
        private struct BalanceResult
        {
            public int nResult;
            public long dwCorpId;
            public int nStaffId;
            public float fRemain;
        }

        // 接口地址
        private static readonly string POST_URL = "http://smsapi.c123.cn/OpenPlatform/OpenApi";

        // 接口帐号, 请换成你的帐号, 格式为 1001@+8位登录帐号+0001
        private static readonly string ACCOUNT = "1001@500819400002";   //新账号，用于验证码发送
        //private static readonly string ACCOUNT = "1001@500819500001"; //test wrong account

        // 接口密钥, 请换成你的帐号对应的接口密钥
        private static readonly string AUTHKEY = "D09296C8957D5653625D5BAE2ACCD7C5";    //新密钥，用于短信验证码发送

        // 通道组编号, 请换成你的帐号可以使用的通道组编号
        private static readonly uint CGID = 3753;

        /************************************************************************/
        /* UrlEncode
        /* 对指定字符串进行URL标准化转码
        /************************************************************************/
        private static string UrlEncode(string text, Encoding encoding)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byData = encoding.GetBytes(text);
            for (int i = 0; i < byData.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byData[i], 16));
            }
            return sb.ToString();
        }

        /************************************************************************/
        /* sendQuery
        /* 向指定的接口地址POST数据并返回响应数据
        /************************************************************************/
        private static string sendQuery(string url, string param)
        {
            // 准备要POST的数据
            byte[] byData = Encoding.UTF8.GetBytes(param);

            // 设置发送的参数
            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            req.Method = "POST";
            req.Timeout = 5000;
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = byData.Length;

            // 提交数据
            Stream rs = req.GetRequestStream();
            rs.Write(byData, 0, byData.Length);
            rs.Close();

            // 取响应结果
            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);

            try
            {
                return sr.ReadToEnd();
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }

            sr.Close();
            return null;
        }


        /************************************************************************/
        /* sendQuery
        /* 向指定的接口地址POST数据并返回响应数据
        /************************************************************************/
        public static string postJson(string url, string param, string token = null)
        {
            // 准备要POST的数据
            byte[] byData = Encoding.UTF8.GetBytes(param);

            // 设置发送的参数
            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            req.Method = "POST";
            req.Timeout = 5000;
            req.ContentType = "application/json";
            req.ContentLength = byData.Length;

            if (!string.IsNullOrWhiteSpace(token))
            {
                req.Headers.Add("Authorization", $"Bearer {token}");
            }

            // 提交数据
            Stream rs = req.GetRequestStream();
            rs.Write(byData, 0, byData.Length);
            rs.Close();

            // 取响应结果
            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);

            try
            {
                return sr.ReadToEnd();
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }

            sr.Close();
            return null;
        }

        /************************************************************************/
        /* 分析返回的结果值
        /************************************************************************/
        private static int parseResult(string sResult)
        {
            if (sResult != null)
            {
                try
                {
                    // 对返回值分析
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(sResult);
                    XmlElement root = xml.DocumentElement;
                    string sRet = root.GetAttribute("result");
                    return Convert.ToInt32(sRet);
                }
                catch (System.Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            return -100;
        }

        private static BalanceResult parseBalanceResult(string sResult)
        {
            BalanceResult ret = new BalanceResult();
            int nRet = parseResult(sResult);
            ret.nResult = nRet;
            if (nRet < 0) return ret;

            try
            {
                // 对返回值分析
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(sResult);
                XmlElement root = xml.DocumentElement;
                if (nRet > 0)
                {
                    XmlNode item = xml.SelectSingleNode("/xml/Item");
                    if (item != null)
                    {
                        ret.dwCorpId = Convert.ToInt64(item.Attributes["cid"].Value);
                        ret.nStaffId = Convert.ToInt32(item.Attributes["sid"].Value);
                        ret.fRemain = (float)Convert.ToDouble(item.Attributes["remain"].Value);
                    }
                }
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return ret;
        }

        /************************************************************************/
        /* 取帐号余额
        /************************************************************************/
        private static BalanceResult getBalance()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("action=getBalance&ac=");
            sb.Append(ACCOUNT);
            sb.Append("&authkey=");
            sb.Append(AUTHKEY);

            string sResult = sendQuery(POST_URL, sb.ToString());
            return parseBalanceResult(sResult);
        }

        /************************************************************************/
        /* 群发接口
        /* 手机号码, 如有多个使用逗号分隔, 支持1~3000个号码
        /* 内容, 500字以内 
        /************************************************************************/
        public static int sendOnce(string mobile, string content, uint uCgid, uint uCsid)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("action=sendOnce&ac=");
            sb.Append(ACCOUNT);
            sb.Append("&authkey=");
            sb.Append(AUTHKEY);
            sb.Append("&cgid=");
            sb.Append(uCgid > 0 ? uCgid : CGID);
            if (uCsid > 0)
            {
                sb.Append("&csid=");
                sb.Append(uCsid);
            }
            sb.Append("&m=");
            sb.Append(mobile);
            sb.Append("&c=");
            sb.Append(UrlEncode(content, Encoding.UTF8));

            string sResult = sendQuery(POST_URL, sb.ToString());
            return parseResult(sResult);
        }

        /************************************************************************/
        /* 群发接口
        /* 手机号码, 如有多个使用逗号分隔, 支持1~3000个号码
        /* 内容, 500字以内 
        /************************************************************************/
        public static int sendOnce(string mobile, string content)
        {
            uint uCgid = 0;
            uint uCsid = 0;
            StringBuilder sb = new StringBuilder();
            sb.Append("action=sendOnce&ac=");
            sb.Append(ACCOUNT);
            sb.Append("&authkey=");
            sb.Append(AUTHKEY);
            sb.Append("&cgid=");
            sb.Append(uCgid > 0 ? uCgid : CGID);
            if (uCsid > 0)
            {
                sb.Append("&csid=");
                sb.Append(uCsid);
            }
            sb.Append("&m=");
            sb.Append(mobile);
            sb.Append("&c=");
            sb.Append(UrlEncode(content, Encoding.UTF8));

            string sResult = sendQuery(POST_URL, sb.ToString());
            return parseResult(sResult);
        }
        /************************************************************************/
        /* 一对一批量发送接口
        /* 手机号码, 如有多个使用逗号分隔, 支持2~100个号码
        /* 内容, 500字以内, 多个用{|}分隔
        /************************************************************************/
        private static int sendBatch(string mobile, string content, uint uCgid, uint uCsid)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("action=sendBatch&ac=");
            sb.Append(ACCOUNT);
            sb.Append("&authkey=");
            sb.Append(AUTHKEY);
            sb.Append("&cgid=");
            sb.Append(uCgid > 0 ? uCgid : CGID);
            if (uCsid > 0)
            {
                sb.Append("&csid=");
                sb.Append(uCsid);
            }
            sb.Append("&m=");
            sb.Append(mobile);
            sb.Append("&c=");
            sb.Append(UrlEncode(content, Encoding.UTF8));

            string sResult = sendQuery(POST_URL, sb.ToString());
            return parseResult(sResult);
        }

        /************************************************************************/
        /* 一对一批量发送接口
        /* 手机号码, 如有多个使用逗号分隔, 支持2~100个号码
        /* 内容, 500字以内, 多个用{|}分隔
        /************************************************************************/
        private static int sendBatch(string mobile, string content)
        {
            uint uCgid = 0;
            uint uCsid = 0;
            StringBuilder sb = new StringBuilder();
            sb.Append("action=sendBatch&ac=");
            sb.Append(ACCOUNT);
            sb.Append("&authkey=");
            sb.Append(AUTHKEY);
            sb.Append("&cgid=");
            sb.Append(uCgid > 0 ? uCgid : CGID);
            if (uCsid > 0)
            {
                sb.Append("&csid=");
                sb.Append(uCsid);
            }
            sb.Append("&m=");
            sb.Append(mobile);
            sb.Append("&c=");
            sb.Append(UrlEncode(content, Encoding.UTF8));

            string sResult = sendQuery(POST_URL, sb.ToString());
            return parseResult(sResult);
        }

        /************************************************************************/
        /* 动态参数发送接口
        /* 手机号码, 如有多个使用逗号分隔, 支持2~100个号码
        /* 内容, 500字以内, 允许使用{p1}~{p10}指定最大10个动态参数
        /* 参数数组, 每个参数的值和号码数相同, 值之间用{|}分隔 
        /************************************************************************/
        private static int sendParam(string mobile, string content, string[] param, uint uCgid, uint uCsid)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("action=sendParam&ac=");
            sb.Append(ACCOUNT);
            sb.Append("&authkey=");
            sb.Append(AUTHKEY);

            for (int i = 0; i < param.Length; i++)
            {
                if (param[i] != null && param[i].Length > 0)
                {
                    sb.Append("&p");
                    sb.Append(i + 1);
                    sb.Append("=");
                    sb.Append(param[i]);
                }
            }

            sb.Append("&cgid=");
            sb.Append(uCgid > 0 ? uCgid : CGID);
            if (uCsid > 0)
            {
                sb.Append("&csid=");
                sb.Append(uCsid);
            }
            sb.Append("&m=");
            sb.Append(mobile);
            sb.Append("&c=");
            sb.Append(UrlEncode(content, Encoding.UTF8));

            string sResult = sendQuery(POST_URL, sb.ToString());
            return parseResult(sResult);
        }

        /************************************************************************/
        /* 动态参数发送接口
        /* 手机号码, 如有多个使用逗号分隔, 支持2~100个号码
        /* 内容, 500字以内, 允许使用{p1}~{p10}指定最大10个动态参数
        /* 参数数组, 每个参数的值和号码数相同, 值之间用{|}分隔 
        /************************************************************************/
        private static int sendParam(string mobile, string content, string[] param)
        {
            uint uCgid = 0;
            uint uCsid = 0;
            StringBuilder sb = new StringBuilder();
            sb.Append("action=sendParam&ac=");
            sb.Append(ACCOUNT);
            sb.Append("&authkey=");
            sb.Append(AUTHKEY);

            for (int i = 0; i < param.Length; i++)
            {
                if (param[i] != null && param[i].Length > 0)
                {
                    sb.Append("&p");
                    sb.Append(i + 1);
                    sb.Append("=");
                    sb.Append(param[i]);
                }
            }

            sb.Append("&cgid=");
            sb.Append(uCgid > 0 ? uCgid : CGID);
            if (uCsid > 0)
            {
                sb.Append("&csid=");
                sb.Append(uCsid);
            }
            sb.Append("&m=");
            sb.Append(mobile);
            sb.Append("&c=");
            sb.Append(UrlEncode(content, Encoding.UTF8));

            string sResult = sendQuery(POST_URL, sb.ToString());
            return parseResult(sResult);
        }
    }

    public partial class MyService
    {
        public Dictionary<string, string> GetAppidSecretDic(string type)
        {
            Dictionary<string, string> ret = new Dictionary<string, string>();
            if (type.Equals("Qgzs"))
            {
                //青贯助手
                ret.Add("appid", "wx51121eaa5bf4584b");
                ret.Add("secret", "62dcf05a146917992bd64257b4ea39e0");
            }
            else if (type.Equals("Fmtzs"))
            {
                //飞毛腿助手
                ret.Add("appid", "wx00d978ec6044cc5a");
                ret.Add("secret", "b5be9cde141709384da5def08e90814b");
            }
            else if (type.Equals("Qgsc"))
            {
                //青贯商城
                ret.Add("appid", "wxffffe95f3a94ca13");
                ret.Add("secret", "c63b873a92d0802659e5308e06e642ce");
            }
            else if ("hongda".Equals(type))
            {
                ret.Add("appid", "wx749b9af7424c2666");
                ret.Add("secret", "f92e73a067e1fdc44acb4555915a630f");
            }
            else if ("juhesell".Equals(type))
            {
                ret.Add("appid", "wx6b03435c3c847b24");
                ret.Add("secret", "0d1744fffa52734fff65ec4f867e1beb");
            }
            else if ("laodinpo".Equals(type))
            {
                ret.Add("appid", "wx9dd93984bf291011");
                ret.Add("secret", "8ddb2992cb58bbebac2919c7ee440e49");
            }
            return ret;
        }
        public string HttpPostWebService(string url, string methodName, string param)
        {
            try
            {
                object[] args = new object[1];
                string strmpl = param;
                args[0] = strmpl;

                string CODEMY_NAMESPACE = "MyWeiXinService";
                //获取Web Service描述     
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(url + "?WSDL");  //这里指定你自己的web service url，一定要以?WSDL结尾    
                ServiceDescription sd = ServiceDescription.Read(stream);
                string classname = sd.Services[0].Name;
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.ProtocolName = "soap";
                sdi.Style = ServiceDescriptionImportStyle.Client;
                sdi.AddServiceDescription(sd, null, null);
                //指定命名空间     
                CodeNamespace cn = new CodeNamespace(CODEMY_NAMESPACE);  //这里随便指定一个命名空间，但要与后面的一致     
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                //建立C#编译器    
                CSharpCodeProvider csc = new CSharpCodeProvider();
                ICodeCompiler icc = csc.CreateCompiler();
                CompilerParameters cp = new CompilerParameters();
                cp.GenerateExecutable = false;
                cp.GenerateInMemory = true;
                //添加编译条件     
                cp.ReferencedAssemblies.Add("System.dll");
                cp.ReferencedAssemblies.Add("System.XML.dll");
                cp.ReferencedAssemblies.Add("System.Web.Services.dll");
                cp.ReferencedAssemblies.Add("System.Data.dll");
                //编译程序集     
                CompilerResults cr = icc.CompileAssemblyFromDom(cp, ccu);
                //检查是否编译成功     
                if (!cr.Errors.HasErrors)
                {
                    //编译成功     
                    //获取程序集     
                    Assembly assembly = cr.CompiledAssembly;
                    //获取程序集类型     
                    //前面的Test就是命名空间，必须要与前面指定的一致     
                    //后面的TestService就是service的类名     
                    //如果所有的服务器都是一致的类名，这里就可以写死，否则要动态提供类名     
                    Type type = assembly.GetType(CODEMY_NAMESPACE + "." + classname, true, true);
                    object service = Activator.CreateInstance(type);
                    //获取方法     
                    //如果所有的服务器都是一致的方法名，这里可以写死，否则就要动态提供方法名     
                    MethodInfo mi = type.GetMethod(methodName);
                    //调用方法     
                    //如果方法没有参数，第二个参数可以传递null，否则就要传递object数组，数组元素的顺序要与参数的顺序一致     
                    //如果所有服务器的方法签名都是一致的，object数组的顺序就可以写死了，否则还要动态调整元素的数量及顺序     
                    return Convert.ToString(mi.Invoke(service, args));
                    //最后，返回的是object类型，根据方法的签名，把返回值转换成不同的对象即可。     
                }
                else
                {
                    //这里自己处理编译错误    
                    return "error";
                }
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }



        private string GetPhoneStringarrin(mysqlcli mainsql, DataRow userrow, string companyaccount = "")
        {
            string retstr = "";

            string user_conphone = userrow["user_conphone"].ToString();
            string phone = userrow["user_phone"].ToString();
            retstr = "'" + phone + "'";
            if (user_conphone.Length > 0)
            {
                string[] phonearr = user_conphone.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (phonearr.Length > 0)
                {
                    retstr = "'" + phone + "','" + string.Join("','", phonearr) + "'";
                }
            }

            if (companyaccount == "")
            {
                return retstr;
            }

            string sqlcmd = string.Format("SELECT * FROM {0}  where yct_phone ='{1}' AND yct_companyaccount='{2}' AND yct_status='已通过' ;"
                , BIAOYONGCOMTELEPHONE, phone, companyaccount);

            DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);

            if (ds.Rows.Count != 0)
            {
                foreach (DataRow row in ds.Rows)
                {
                    retstr += ",'" + row["yct_telephone"].ToString() + "'";
                }
            }

            return retstr;

        }




        //获取openid
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_GetOpenId(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
            logJieKou.Info("获取用户的openid-" + logip);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                string type = "laodinpo";
                if (comrcv.Map_Args.ContainsKey("type"))
                {
                    type = comrcv.Map_Args["type"];
                }
                Dictionary<string, string> appidsecret = GetAppidSecretDic(type);
                string appid = appidsecret["appid"];
                string secret = appidsecret["secret"];
                string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + comrcv.Map_Args["code"] + "&grant_type=authorization_code";
                WebRequest request = (WebRequest)HttpWebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                string result = string.Empty;
                using (WebResponse response = request.GetResponse())
                {
                    if (response != null)
                    {
                        using (Stream stream = response.GetResponseStream())
                        {
                            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                            {
                                result = reader.ReadToEnd();
                            }
                        }
                    }
                }
                logJieKou.Info("获取用户的openid-" + result);

                JObject job = (JObject)JsonConvert.DeserializeObject(result);
                string openid = job["openid"].ToString();
                string session_key = job["session_key"].ToString();

                ret.Map_Args.Add("OpenId", openid);
                ret.Map_Args.Add("Session", session_key);

                ret.Byte_Flag = 1;
                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误
            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }


        /// <summary>
                /// AES解密：从小程序中 getPhoneNumber 返回值中，解析手机号码
                /// </summary>
                /// <param name="encryptedData">包括敏感数据在内的完整用户信息的加密数据，详细见加密数据解密算法</param>
                /// <param name="IV">加密算法的初始向量</param>
                /// <param name="Session_key"></param>
        /// <returns>手机号码</returns>
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_GetPhoneNumber(string msg)
        {

            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
            logJieKou.Info("解密用户的手机号码-" + logip);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }

                string encryptedData = comrcv.Map_Args["encryptedData"];
                string IV = comrcv.Map_Args["iv"];
                string Session_key = comrcv.Map_Args["sessionKey"];
                byte[] encryData = Convert.FromBase64String(encryptedData);  // strToToHexByte(text);
                RijndaelManaged rijndaelCipher = new RijndaelManaged();
                rijndaelCipher.Key = Convert.FromBase64String(Session_key); // Encoding.UTF8.GetBytes(AesKey);
                rijndaelCipher.IV = Convert.FromBase64String(IV);// Encoding.UTF8.GetBytes(AesIV);
                rijndaelCipher.Mode = CipherMode.CBC;
                rijndaelCipher.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                string result = Encoding.Default.GetString(plainText);
                //动态解析result 成对象
                //dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;

                JObject job = (JObject)JsonConvert.DeserializeObject(result);
                string phoneNumber = job["phoneNumber"].ToString();
                ret.Map_Args.Add("Phone", phoneNumber);

                ret.Byte_Flag = 1;
                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误

            }
            catch (Exception ex)
            {
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }


        //查询所有区域的所有公司并返回公司信息
        [WebMethod(Description = "基础调用")]
        public string XCXYunLi_GetALLCompanyAndArea(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
            logJieKou.Info("查询所有区域的所有公司并返回公司信息-" + logip);
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                mainsql.openYunLiServicesql();

                string sqlcmd = string.Format("SELECT *  FROM {0} ", BIAOQUYUNAME);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "没有任何区域";  //参数错误
                    goto EXIT;
                }
                List<Dictionary<string, string>> List_MapArgs = new List<Dictionary<string, string>>();
                ret.Map_Args.Add("qy_count", ds.Rows.Count.ToString());
                for (int i = 0; i < ds.Rows.Count; i++)
                {
                    string qynumber = ds.Rows[i]["qy_number"].ToString();

                    ret.Map_Args.Add("qy_number" + (i + 1).ToString(), qynumber);
                    ret.Map_Args.Add("qy_name" + (i + 1).ToString(), ds.Rows[i]["qy_name"].ToString());

                    sqlcmd = string.Format("SELECT {0}.*  FROM {0},{1} where {1}.con_quyunumber='{2}' AND {1}.con_companyaccount={0}.com_number",
                        BIAOCOMPANYNAME, BIAOCONQUYU_COMPANY, qynumber);
                    DataTable comds = mainsql.SqlExcuteWithReturn(sqlcmd);
                    if (comds.Rows.Count != 0)
                    {
                        foreach (DataRow row in comds.Rows)
                        {
                            Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                            newNetImple.Add("qy_number", qynumber);
                            foreach (DataColumn dl in comds.Columns)
                            {
                                newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                            }
                            List_MapArgs.Add(newNetImple);
                        }
                    }
                }
                ret.List_MapArgs = List_MapArgs;
                ret.Byte_Flag = 1;
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //根据手机号码返回用户信息
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_GetYongHuByPhone(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            var isjson = true;
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                logJieKou.Info("根据手机号码返回用户信息-" + comrcv.Map_Args["phone"]);
                mainsql.openYongHuServicesql();
                int bindcount = comrcv.Byte_Flag;
                if (bindcount == 1)
                {
                    string phone = comrcv.Map_Args["phone"];
                    if (string.IsNullOrWhiteSpace(phone))
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "号码不能为空";  //参数错误
                        goto EXIT;
                    }

                    string sqlcmd = $@"select b.vip_frame_no,b.vip_license_plate_no,b.vip_name ,a.* from {BIAOYONGHUUSER} a left join s_vip b on a.user_phone = b.vip_phone where user_phone = '{phone}'";

                    //string sqlcmd = string.Format("SELECT * FROM {0}  where user_phone ='{1}'", BIAOYONGHUUSER, phone);
                    DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "找不到相关数据";  //参数错误
                        goto EXIT;
                    }
                    ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                    ret.List_MapArgs = new List<Dictionary<string, string>>();
                    var companyid = string.Empty;
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                            if ("companyid".Equals(dl.ColumnName))
                            {
                                companyid = row[dl.ColumnName].ToString();
                            }
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }

                }
                else
                {
                    ret.Map_Args["ErrorMsg"] = "参数错误";  //参数错误
                    goto EXIT;
                }
                ret.Byte_Flag = 1;
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //根据微信标志位返回用户信息
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_GetYongHuByWeiXin(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Maplist_MapArgs = new Dictionary<string, List<Dictionary<string, string>>>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                logJieKou.Info("根据微信标志位返回用户信息-" + comrcv.Map_Args["openid"]);
                mainsql.openYongHuServicesql();
                int bindcount = comrcv.Byte_Flag;
                if (bindcount == 1)
                {
                    string openid = comrcv.Map_Args["openid"];
                    string xcxopenidkey = "user_xcxopenid";

                    string sql = $@"select b.vip_frame_no,b.vip_license_plate_no,b.vip_name ,a.* from {BIAOYONGHUUSER} a left join s_vip b on a.user_phone = b.vip_phone where {xcxopenidkey} = '{openid}'";

                    //string sqlcmd = string.Format("SELECT * FROM {0}  where {2} ='{1}'", BIAOYONGHUUSER, openid, xcxopenidkey);
                    DataTable ds = mainsql.SqlExcuteWithReturn(sql);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "找不到相关数据";  //参数错误
                        goto EXIT;
                    }
                    else if (ds.Rows.Count != 1)
                    {
                        sql = string.Format("update {0} set {2}='' where {2} ='{1}'",
                        BIAOYONGHUUSER, openid, xcxopenidkey);
                        int sqlret = mainsql.SqlExcuteNoReturn(sql);

                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "找不到相关数据";  //参数错误
                        goto EXIT;
                    }

                    ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                    ret.List_MapArgs = new List<Dictionary<string, string>>();
                    var companyid = string.Empty;
                    foreach (DataRow row in ds.Rows)
                    {
                        Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                        foreach (DataColumn dl in ds.Columns)
                        {

                            if ("companyid".Equals(dl.ColumnName))
                            {
                                companyid = row[dl.ColumnName].ToString();
                            }
                            if ("user_tuiguanglevel".Equals(dl.ColumnName))
                            {
                                row[dl.ColumnName] = "0";
                            }
                            newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                        }
                        ret.List_MapArgs.Add(newNetImple);
                    }

                }
                else
                {
                    ret.Map_Args["ErrorMsg"] = "参数错误";  //参数错误
                    goto EXIT;
                }

                ret.Map_Args.Add("isopenhuokuanbao", System.Configuration.ConfigurationManager.AppSettings["isopenhuokuanbao"]);

                ret.Byte_Flag = 1;
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //修改用户资料
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_ChangeInfo(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            var isjson = true;
            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    byte[] bytrcv = Convert.FromBase64String(msg);
                    ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
                    if (!comrcv.__isset.byte_Flag)
                    {
                        ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                        goto EXIT;
                    }
                    if (comrcv.Byte_Flag != 1)
                    {
                        ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                        goto EXIT;
                    }

                    string user_phone = comrcv.Map_Args["phone"];
                    string user_name = comrcv.Map_Args["name"];

                    string user_address = comrcv.Map_Args["user_address"];
                    string user_othertuiguangid = "";
                    if (comrcv.Map_Args.ContainsKey("user_othertuiguangid") == true)
                    {
                        user_othertuiguangid = comrcv.Map_Args["user_othertuiguangid"];
                    }

                    logJieKou.Info("修改用户资料-" + user_phone);
                    mainsql.openYongHuServicesql();
                    string sqlcmd = string.Format("SELECT * FROM {0}  where user_phone ='{1}';", BIAOYONGHUUSER, user_phone);
                    DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "手机号码关联的账号不存在";  //参数错误
                        goto EXIT;
                    }
                    var userid = ds.Rows[0]["companyid"]?.ToString();
                    var companyid = comrcv.Map_Args.ContainsKey("companyid") ? comrcv.Map_Args["companyid"] : string.Empty;

                    if (string.IsNullOrWhiteSpace(companyid))
                    {
                        if (!string.IsNullOrWhiteSpace(userid))
                            companyid = userid;
                        else
                            companyid = ds.Rows[0]["user_onlyid"].ToString();
                    }

                    sqlcmd = string.Format("update {0} set companyid='{1}',user_name='{2}',user_address='{3}',user_othertuiguangid='{4}' where user_phone ='{5}'",
                        BIAOYONGHUUSER, companyid, user_name, user_address, user_othertuiguangid, user_phone);
                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "修改失败";  //参数错误
                        goto EXIT;
                    }

                    ret.Byte_Flag = 1;
                    tsall.Complete();
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误

                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //修改推广
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_ChangeTuiGuang(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            var isjson = true;
            try
            {
                using (TransactionScope tsall = new TransactionScope())
                {
                    byte[] bytrcv = Convert.FromBase64String(msg);
                    ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv, ref isjson);
                    if (!comrcv.__isset.byte_Flag)
                    {
                        ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                        goto EXIT;
                    }
                    if (comrcv.Byte_Flag != 1)
                    {
                        ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                        goto EXIT;
                    }

                    string user_onlyid = comrcv.Map_Args["user_onlyid"];

                    string user_othertuiguangid = "";
                    if (comrcv.Map_Args.ContainsKey("user_othertuiguangid") == true)
                    {
                        user_othertuiguangid = comrcv.Map_Args["user_othertuiguangid"];
                    }



                    mainsql.openYongHuServicesql();
                    string sqlcmd = string.Format("SELECT * FROM {0}  where user_onlyid ='{1}';", BIAOYONGHUUSER, user_onlyid);
                    DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "账号不存在";  //参数错误
                        goto EXIT;
                    }
                    if (ds.Rows[0]["user_othertuiguangid"]?.ToString() != "")
                    {

                        sqlcmd = string.Format("update {0} set user_othertuiguangid='{1}'  where user_onlyid ='{2}'",
                            BIAOYONGHUUSER, user_othertuiguangid, user_onlyid);
                        int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                        if (sqlret != 1)
                        {
                            mainsql.closesql();
                            ret.Map_Args["ErrorMsg"] = "修改失败";  //参数错误
                            goto EXIT;
                        }
                    }

                    ret.Byte_Flag = 1;
                    tsall.Complete();
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误

                }
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret, isjson);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }



        //绑定微信标志和手机号
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_SetBindWeiXin(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }


                string openid = comrcv.Map_Args["openid"];
                string phone = comrcv.Map_Args["phone"];
                string user_othertuiguangid = "";
                if (comrcv.Map_Args.ContainsKey("user_othertuiguangid") == true)
                {
                    user_othertuiguangid = comrcv.Map_Args["user_othertuiguangid"];
                }
                string xcxopenidkey = "user_xcxopenid";

                logJieKou.Info("绑定微信标志和手机号-" + phone);
                mainsql.openYongHuServicesql();
                string sqlcmd = string.Format("SELECT * FROM {0}  where user_phone ='{1}'", BIAOYONGHUUSER, phone);
                var user = mainsql.SqlExcuteWithReturn(sqlcmd).ToModels().FirstOrDefault();
                if (user == null)
                {
                    string idkeystr = Guid.NewGuid().ToString();
                    sqlcmd = string.Format("INSERT INTO {0} (user_phone,{4},user_createtime,user_onlyid,user_othertuiguangid) VALUES ('{1}','{2}','{3}','{5}','{6}')",
                    BIAOYONGHUUSER, phone, openid, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), xcxopenidkey, idkeystr, user_othertuiguangid);
                    logJieKou.Info(sqlcmd);
                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "插入数据失败";  //参数错误
                        goto EXIT;
                    }

                    //分享者送优惠券
                    if (comrcv.Map_Args.Keys.Contains("sid"))
                    {
                        string sid = comrcv.Map_Args["sid"];

                        //用户是否存在
                        sqlcmd = $"select * from yonghualluser where Sid='{sid}'";
                        var shareUser = mainsql.SqlExcuteWithReturn(sqlcmd).ToModels().FirstOrDefault();

                        if (shareUser != null)
                        {
                            //string yhqid = GetYHQID();
                            //sqlcmd = $@"INSERT INTO s_coupon 
                            //        (Sid,user_id,user_phone,coupon_createtime,coupon_status ,coupon_describe,coupon_endtime,coupon_amount,yhq_shuoming,yhq_createtime,yhq_source)
                            //         VALUES 
                            //        ('{yhqid}','{shareUser["user_phone"]}','{shareUser["user_onlyid"]}','0','1','未使用','40','{DateTime.Now.AddYears(1)}','用户分享获得现金券40元','{DateTime.Now}',2)";

                            //mainsql.SqlExcuteNoReturn(sqlcmd);
                        };
                    }

                }
                else
                {
                    sqlcmd = string.Format("update {0} set {3}='{1}' where user_phone ='{2}'",
                        BIAOYONGHUUSER, openid, phone, xcxopenidkey);
                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "绑定失败";  //参数错误
                        goto EXIT;
                    }
                }

                ret.Byte_Flag = 1;
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //解除绑定微信标志和手机号
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_CancelBindWeiXin(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                logJieKou.Info("解除绑定微信标志和手机号-" + comrcv.Map_Args["openid"]);
                mainsql.openYongHuServicesql();
                int bindcount = comrcv.Byte_Flag;
                if (bindcount == 1)
                {
                    string openid = comrcv.Map_Args["openid"];
                    string xcxopenidkey = "user_xcxopenid";

                    string sqlcmd = string.Format("SELECT * FROM {0}  where {2} ='{1}'", BIAOYONGHUUSER, openid, xcxopenidkey);
                    DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                    if (ds.Rows.Count == 0)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "未查找到关联数据";  //参数错误
                        goto EXIT;
                    }
                    sqlcmd = string.Format("update {0} set {2}='' where {2} ='{1}'",
                     BIAOYONGHUUSER, openid, xcxopenidkey);
                    int sqlret = mainsql.SqlExcuteNoReturn(sqlcmd);
                    if (sqlret != 1)
                    {
                        mainsql.closesql();
                        ret.Map_Args["ErrorMsg"] = "修改数据失败";  //参数错误
                        goto EXIT;
                    }
                }
                else
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "参数错误";  //参数错误
                    goto EXIT;
                }
                ret.Byte_Flag = 1;
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //微信平台用户上传一张认证照片
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_UploadRenZhengPic(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }


                string phone = comrcv.Map_Args["phone"];

                logJieKou.Info("微信平台用户上传一张认证照片-" + phone);

                mainsql.openYongHuServicesql();
                string sqlcmd = string.Format("SELECT * FROM {0}  where user_phone ='{1}'", BIAOYONGHUUSER, phone);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "手机号码关联的账号不存在";  //参数错误
                    goto EXIT;
                }
                string FileName = comrcv.Map_Args["filename"];//phone.png
                string BuffLengthstr = comrcv.Map_Args["bufflength"];
                int BuffLength = 0;
                int.TryParse(BuffLengthstr, out BuffLength);
                byte[] valuebyte = Convert.FromBase64String(comrcv.Map_Args["buffbyte"]);
                string PathStr = "D://YunLiUserPic//" + FileName;
                if (File.Exists(PathStr))
                {
                    FileStream fs = new FileStream(PathStr, FileMode.Append);//重新定义
                    fs.Write(valuebyte, 0, BuffLength);
                    fs.Close();
                }
                string dir = Path.GetDirectoryName(PathStr);
                Directory.CreateDirectory(dir);
                FileStream fs1 = new FileStream(PathStr, FileMode.OpenOrCreate);//重新定义
                fs1.Write(valuebyte, 0, BuffLength);
                fs1.Close();


                string cmd = string.Format("UPDATE {0} SET user_renzhengpicname= '{1}',user_renzhengstatus='等待认证'  " +
                "WHERE user_phone = '{2}'", BIAOYONGHUUSER, FileName, phone);
                int sqlret = mainsql.SqlExcuteNoReturn(cmd);
                if (sqlret != 1)
                {
                    mainsql.closesql();
                    goto EXIT;
                }
                ret.Byte_Flag = 1;
                mainsql.closesql();

            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }
        //微信平台用户下载一张认证照片
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_DownloadRenZhengPic(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                string phone = comrcv.Map_Args["phone"];
                logJieKou.Info("微信平台用户下载一张认证照片-" + phone);
                mainsql.openYongHuServicesql();
                string sqlcmd = string.Format("SELECT * FROM {0}  where user_phone ='{1}'", BIAOYONGHUUSER, phone);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "手机号码关联的账号不存在";  //参数错误
                    goto EXIT;
                }
                string Filename = ds.Rows[0]["user_renzhengpicname"].ToString();
                string PathStr = "D://YunLiUserPic//" + Filename;
                if (File.Exists(PathStr))
                {
                    FileInfo fileInf = new FileInfo(PathStr);
                    int buffLength = (int)fileInf.Length;
                    byte[] bytes = new byte[buffLength];
                    FileStream fs = fileInf.OpenRead();
                    int contentLen = fs.Read(bytes, 0, buffLength);

                    ret.Map_Args.Add("FileString", Convert.ToBase64String(bytes));
                    ret.Byte_Flag = 1;
                    fs.Dispose();
                }
                else
                {
                    ret.Byte_Flag = -1;
                    ret.Map_Args["ErrorMsg"] = "无路径文件";
                    goto EXIT;
                }
                ret.Byte_Flag = 1;
                mainsql.closesql();

            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //根据手机号码发送验证短信
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_SendSms(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();
            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                logJieKou.Info("根据手机号码返回用户信息-" + comrcv.Map_Args["phone"]);

                Random rnd = new Random(Environment.TickCount);
                string psw = rnd.Next(100000, 999999).ToString();
                string pswstr = string.Format("您的手机正在登录青贯微信公众平台，验证码为：{0},如非本人操作，请忽略本条短信并且不要将此条短信内容告知他人。"
               , psw);
                SmsSendInterface.sendOnce(comrcv.Map_Args["phone"], pswstr);

                ret.Map_Args.Add("YanZheng", psw);
                ret.Byte_Flag = 1;

                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误
            }
            catch (Exception ex)
            {

                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //根据手机号返回用户历史订单记录
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_GetDingDanByPhone(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            try
            {
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.Json_ByteTOComThriftAESD(bytrcv);
                if (!comrcv.__isset.byte_Flag)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                if (comrcv.Byte_Flag != 1)
                {
                    ret.Map_Args["ErrorMsg"] = "解析失败";  //参数错误
                    goto EXIT;
                }
                string phone = comrcv.Map_Args["phone"];
                logJieKou.Info("订单-根据手机号返回用户历史订单记录-" + phone);
                mainsql.openYongHuServicesql();

                string whereadd = string.Format(" dd_createaccount ='{0}' ", phone);

                if (comrcv.Map_Args.ContainsKey("xiadanonly") == true)
                {
                    whereadd += " AND dd_status = '已下单' ";
                }
                if (comrcv.Map_Args.ContainsKey("companyaccount") == true)
                {
                    whereadd += string.Format(" AND dd_yunlicompanyaccount ='{0}' ", comrcv.Map_Args["companyaccount"]);
                }

                string sqlcmd = "";

                if (comrcv.Map_Args.ContainsKey("datetime") == true)
                {
                    sqlcmd = string.Format("select * from {0} where   {1}  ORDER BY dd_createtime DESC limit 50 ;",
                        BIAOYONGHUDINGDANBIAO + comrcv.Map_Args["datetime"], whereadd, comrcv.Map_Args["companyaccount"]);
                }
                else
                {
                    sqlcmd = string.Format("select * from {0} where   {1} ORDER BY dd_createtime DESC limit 50 ;",
                             BIAOYONGHUDINGDANBIAO + DateTime.Now.ToString("yyyyMM"), whereadd);
                }

                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    ds.Dispose();
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "没有查询到任何记录。";
                    goto EXIT;
                }
                mainsql.closesql();
                ret.Map_Args.Add("AllCount", ds.Rows.Count.ToString());
                ret.List_MapArgs = new List<Dictionary<string, string>>();
                foreach (DataRow row in ds.Rows)
                {
                    Dictionary<string, string> newNetImple = new Dictionary<string, string>();
                    foreach (DataColumn dl in ds.Columns)
                    {
                        newNetImple.Add(dl.ColumnName, row[dl.ColumnName].ToString());
                    }
                    ret.List_MapArgs.Add(newNetImple);
                }

                ret.Byte_Flag = 1;

                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }
            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

        //小程序下发模板通知
        [WebMethod(Description = "基础调用")]
        public string XCXYongHu_SetSendMessage(string msg)
        {
            ILog logJieKou = LogManager.GetLogger("LoggerRecod");
            string logip = Context.Request.ServerVariables.Get("Remote_Addr").ToString();

            ComThriftMsg ret = new ComThriftMsg();
            ret.Byte_Flag = (sbyte)-1;
            ret.Map_Args = new Dictionary<string, string>();
            ret.Map_Args.Add("ErrorMsg", "服务器异常");
            mysqlcli mainsql = new mysqlcli();
            try
            {
                logJieKou.Info("小程序下发模板通知-");
                byte[] bytrcv = Convert.FromBase64String(msg);
                ComThriftMsg comrcv = CommonTools.ByteTOComThriftAESD(bytrcv);

                string id = comrcv.Map_Args["Sid"];
                mainsql.openYongHuServicesql();
                string sqlcmd = string.Format("SELECT * FROM {0}  where Sid ='{1}'", BIAOYONGHULIUYANNAME, id);
                DataTable ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "留言不存在";  //参数错误
                    goto EXIT;
                }

                string phone = ds.Rows[0]["ly_lyrzh"].ToString();
                string Lysj = ds.Rows[0]["ly_lysj"].ToString();
                string Lywz = ds.Rows[0]["ly_lywz"].ToString();
                string Sjly = ds.Rows[0]["ly_sjly"].ToString();
                string Hfwz = ds.Rows[0]["ly_hfwz"].ToString();

                string OPENID = "";
                string tempid = "";

                sqlcmd = string.Format("SELECT * FROM {0}  where user_phone ='{1}'", BIAOYONGHUUSER, phone);


                logJieKou.Info("小程序下发模板通知-" + phone);

                ds = mainsql.SqlExcuteWithReturn(sqlcmd);
                if (ds.Rows.Count == 0)
                {
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "手机号码关联的账号不存在";  //参数错误
                    goto EXIT;
                }
                string sendmsg = "";

                if (Sjly.Equals("Qgzs"))
                {
                    OPENID = ds.Rows[0]["user_xcxopenid"].ToString();
                    tempid = "LAwAVefkcoviFe1qj3cY02wgfOAi7m9STb8rZy2S-Rg";
                    sendmsg = "{\"touser\": \"" + OPENID + "\", \"template_id\": \"" + tempid + "\", \"page\": \"pages/liuyan/index\",\"data\": {\"thing1\": {\"value\": \"" + Lywz + "\"},\"thing2\": {\"value\": \"" + Hfwz + "\"} }}";
                }

                if (OPENID.Equals(""))
                {
                    logJieKou.Info("openid无模板-" + Sjly);
                    mainsql.closesql();
                    ret.Map_Args["ErrorMsg"] = "openid无模板";  //参数错误
                    goto EXIT;
                }

                Dictionary<string, string> appidsecret = GetAppidSecretDic(Sjly);
                string appid = appidsecret["appid"];
                string secret = appidsecret["secret"];

                string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
                WebRequest request = (WebRequest)HttpWebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                string result = string.Empty;
                using (WebResponse response = request.GetResponse())
                {
                    if (response != null)
                    {
                        using (Stream stream = response.GetResponseStream())
                        {
                            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                            {
                                result = reader.ReadToEnd();
                            }
                        }
                    }
                }
                logJieKou.Info("小程序下发模板通知-" + result);

                JObject job = (JObject)JsonConvert.DeserializeObject(result);
                string access_token = job["access_token"].ToString();

                url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;
                logJieKou.Info("小程序下发模板通知-" + sendmsg);

                request = (WebRequest)HttpWebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                byte[] postBytes = null;
                postBytes = Encoding.UTF8.GetBytes(sendmsg);
                request.ContentLength = postBytes.Length;
                using (Stream outstream = request.GetRequestStream())
                {
                    outstream.Write(postBytes, 0, postBytes.Length);
                }
                using (WebResponse response = request.GetResponse())
                {
                    if (response != null)
                    {
                        using (Stream stream = response.GetResponseStream())
                        {
                            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                            {
                                result = reader.ReadToEnd();
                            }
                        }
                    }
                }
                logJieKou.Info("小程序下发模板通知-" + result);

                ret.Byte_Flag = 1;
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = "调用成功";  //参数错误
            }
            catch (Exception ex)
            {
                mainsql.closesql();
                ret.Map_Args["ErrorMsg"] = ex.Message;  //参数错误
            }


            EXIT:
            byte[] retb = CommonTools.Json_ComThriftTOByteAESE(ret);
            string retstr = Convert.ToBase64String(retb);
            return retstr;
        }

    }


}